<template>
  <div>
    <el-card>
      <!--警告-->
      <el-alert
              title="只提供三级权限的操作!!"
              type="warning"
              show-icon
              :closable="false">
      </el-alert>

      <!--选择器-->
      <el-row class="margin-top-20">
        <el-col>
          选择商品分类:
          <el-cascader
                  v-model="checkedCategory"
                  :options="categories"
                  @change="handleChange" :props="categoryProps"></el-cascader>
        </el-col>
      </el-row>

      <!--标签-->
      <template>
        <el-tabs v-model="activeName" @tab-click="handleClickTabs" class="margin-top-20 margin-bottom-20">
          <el-tab-pane label="动态参数" name="many">
            <el-button type="primary" size="mini" @click="paramDialogVisible = true" :disabled="isDisabled">添加参数</el-button>

            <!--table-->
            <el-table :data="dynamicParam" border stripe class="margin-top-20">
              <el-table-column type="expand" label="#">
                <template slot-scope="scope">
                  <el-tag closable @close="deleteValues(i,scope.row)" v-for="(item,i) in scope.row.attr_vals" :key="i" class="margin-left-10 margin-right-10">
                    {{item}}
                  </el-tag>
                  <el-input
                          class="input-new-tag"
                          v-if="scope.row.inputVisible"
                          v-model="scope.row.inputValue"
                          ref="saveTagInput"
                          size="small"
                          @keyup.enter.native="handleInputConfirm(scope.row)"
                          @blur="handleInputConfirm(scope.row)"
                  >
                  </el-input>
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                </template>
              </el-table-column>
              <el-table-column type="index" label="#"></el-table-column>
              <el-table-column label="参数名称" prop="attr_name"></el-table-column>
              <!--操作-->
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button @click="editParam(scope.row)" type="primary" size="mini">编辑</el-button>
                  <el-button @click="deleteParamBefore(scope.row)" type="danger" size="mini">删除</el-button>
                </template>
              </el-table-column>
            </el-table>


          </el-tab-pane>
          <el-tab-pane label="静态属性" name="only">
            <el-button type="primary" size="mini" @click="paramDialogVisible = true" :disabled="isDisabled">添加属性</el-button>
            <!--table-->
            <el-table :data="staticParam" border stripe class="margin-top-20">
              <el-table-column type="expand" label="#">
                <template slot-scope="scope">
                  <el-tag closable @close="deleteValues(i,scope.row)" v-for="(item,i) in scope.row.attr_vals" :key="i" class="margin-left-10 margin-right-10">
                    {{item}}
                  </el-tag>
                  <el-input
                          class="input-new-tag"
                          v-if="scope.row.inputVisible"
                          v-model="scope.row.inputValue"
                          ref="saveTagInput"
                          size="small"
                          @keyup.enter.native="handleInputConfirm(scope.row)"
                          @blur="handleInputConfirm(scope.row)"
                  >
                  </el-input>
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                </template>
              </el-table-column>
              <el-table-column type="index" label="#"></el-table-column>
              <el-table-column label="参数名称" prop="attr_name"></el-table-column>
              <!--操作-->
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button @click="editParam(scope.row)" type="primary" size="mini">编辑</el-button>
                  <el-button @click="deleteParamBefore(scope.row)" type="danger" size="mini">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </template>
    </el-card>

    <!--dialog add-->
    <el-dialog
            :title="'添加' + getDialogTitle"
            :visible.sync="paramDialogVisible"
            width="30%"
            :before-close="paramHandleClose">

      <el-form label-width="80px" :rules="addFormRules" ref="addFormRef" :model="paramValue" label-position="left">
        <el-form-item :label="getDialogTitle" prop="attr_name">
          <el-input v-model="paramValue.attr_name"></el-input>
        </el-form-item>
      </el-form>

    <el-button @click="paramHandleClose">取 消</el-button>
    <el-button type="primary" @click="addParam">确 定</el-button>
    </el-dialog>

    <!--dialog edit-->
    <el-dialog
            :title="'修改' + getDialogTitle"
            :visible.sync="modifyDialogVisible"
            width="30%"
            :before-close="modifyParamHandleClose">
      <el-form label-width="80px" :rules="addFormRules" ref="modifyFormRef" :model="modifyParamValue" label-position="left">
        <el-form-item :label="getDialogTitle" prop="attr_name">
          <el-input v-model="modifyParamValue.attr_name"></el-input>
        </el-form-item>
      </el-form>
    <el-button @click="modifyParamHandleClose">取 消</el-button>
    <el-button type="primary" @click="modifyParam">确 定</el-button>
    </el-dialog>

    <!--删除前的消息提示-->


  </div>
</template>



<script>
  export default {
    name: "Card",
    data() {
      return {
        categories: [],
        attributes: [],
        checkedCategory: [],
        // 级联选择器的配置
        categoryProps: {
          value: 'cat_id',
          label: 'cat_name',
          children: 'children',
        },
        activeName: 'many',
        staticParam: [],
        dynamicParam: [],
        paramValue: {
          attr_name: '',
        },
        modifyParamValue: {
          attr_id: '',
          attr_name: '',
        },
        paramDialogVisible: false,
        modifyDialogVisible: false,
        addFormRules: {
          attr_name: [
            { required: true, message: '不能为空', trigger: 'blur' }
          ]
        },
        inputVisible: false,
        inputValue: ''
      }
    },

    methods: {
      // 选择器被修改
      handleChange(obj) {
        if (obj.length < 3) {
          this.checkedCategory = []
          this.$message.error('只提供三级权限的操作!!')
          if (this.activeName === 'many') {
            this.dynamicParam = []
          }else {
            this.staticParam = []
          }
          return
        }
        this.getParams()
      },
      getCategories() {
        this.$http.get('categories',{params: {type: 3}}).then(result => {
          if (result.data.meta.status != 200) return this.message.error('获取商品分类失败!!')
          this.categories = result.data.data
        })
      },
      handleClickTabs(tab,event) {

        this.getParams()

      },
      getParams() {
        this.$http.get(`categories/${this.getCateId()}/attributes` ,{params: {sel: this.activeName}}).then(result => {


          if (result.data.meta.status !== 200) return this.$message.error("获取参数失败, " + result.data.meta.msg)

          result.data.data.forEach(item => {
            item.inputVisible = false
            item.inputValue = ''
            item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []

          })

          if (this.activeName === 'only') {
            this.staticParam = result.data.data
          } else {
            this.dynamicParam = result.data.data
          }

          console.log(result.data.data);


        })
      },
      getCateId() {
        if (this.checkedCategory.length === 3) {
          return this.checkedCategory[this.checkedCategory.length-1]
        }
        return null
      },
      editParam(obj) {
        // 通过id查询name
        this.$http.get(`categories/${this.getCateId()}/attributes/${obj.attr_id}`,
            {attr_sel: this.activeName}).then(result => {
          this.modifyParamValue.attr_name = result.data.data.attr_name
          this.modifyParamValue.attr_id = result.data.data.attr_id
        })
        this.modifyDialogVisible = true;
      },
      deletePram(obj) {
        this.$http.delete(`categories/${this.getCateId()}/attributes/${obj.attr_id}`).then(result => {
          if (result.data.meta.status != 200) return this.$message.error(result.data.meta.msg)
          this.getParams()
          return this.$message.success(result.data.meta.msg)
        })

      },
      paramHandleClose() {
        this.paramDialogVisible = false
        this.$refs.addFormRef.resetFields()
      },
      modifyParamHandleClose() {
        this.modifyDialogVisible = false
        this.$refs.modifyFormRef.resetFields()
      },
      addParam() {
        this.$refs.addFormRef.validate(valid => {
          if (!valid || this.checkedCategory.length < 3) return

          //发起请求
          this.$http.post
          (`categories/${this.checkedCategory[this.checkedCategory.length-1]}/attributes`,
              {attr_name: this.paramValue.attr_name , attr_sel: this.activeName})
              .then(result => {
                if (result.data.meta.status !== 201) return this.$message.error("添加失败 , " + result.data.meta.msg)
                this.getParams()
              })

          this.paramDialogVisible = false
          this.$refs.addFormRef.resetFields()
        })
      },
      modifyParam() {
        this.$http.put(`categories/${this.getCateId()}/attributes/${this.modifyParamValue.attr_id}`,
            {attr_name: this.modifyParamValue.attr_name, attr_sel: this.activeName}).then(result => {
          if (result.data.meta.status !== 200) {
            this.modifyDialogVisible = false
            return this.$message.error('修改失败, ' + result.data.meta.msg)
          }
          else {
            this.modifyDialogVisible = false
            this.getParams()
            return this.$message.success(result.data.meta.msg)
          }
          this.modifyParamHandleClose()
        })
      },
      deleteParamBefore (obj) {
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.deletePram(obj)
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      deleteValues(i,obj) {

        obj.attr_vals.splice(i,1)
        this.$http.put(`categories/${this.getCateId()}/attributes/${obj.attr_id}`,
            {attr_name: obj.attr_name,attr_sel: this.activeName, attr_vals: obj.attr_vals.toString()}).then(result => {
          if (result.data.meta.status !== 200) return this.$message.error(result.data.meta.msg)
          this.$message.success(result.data.meta.msg)
        })
      },
      handleInputConfirm(obj) {

        let inputValue = obj.inputValue;
        console.log(inputValue);
        if (inputValue) {
          obj.attr_vals.push(inputValue);
          this.$http.put(`categories/${this.getCateId()}/attributes/${obj.attr_id}`,
              {attr_name: obj.attr_name,attr_sel: this.activeName, attr_vals: obj.attr_vals.toString()}).then(result => {
                if (result.data.meta.status !== 200) return this.$message.error(result.data.meta.msg)
                this.$message.success(result.data.meta.msg)
          })
        }

        obj.inputVisible = false;
        obj.inputValue = '';
      },
      showInput(obj) {

        obj.inputVisible = true;
        /* $nextTick: 当页面上的元素被重新渲染后才会调用指定代deleteValues码 ,
        因为即使inputVisible为true了 , 可能文本框还为渲染出来 ,
        此时去调用saveTagInput是不存在的 */
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
      }
    },
    computed: {
      isDisabled() {
        if (this.checkedCategory.length !== 3) {
          return true
        }
        return false
      },
      getDialogTitle() {
        if (this.activeName === 'many') {
          return "动态参数"
        }
        return "静态属性"
      }
    },
    created() {
      this.getCategories()
    }
  }
</script>

<style scoped>
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>